import requests
import hashlib
import urllib.parse
import time

def get_center(paths):
    flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
    pos_list = flatten(list(map(lambda path: path.split(";"), paths.split("|"))))
    lng_list = list(map(lambda pos: float(pos.split(",")[0]), pos_list))
    lat_list = list(map(lambda pos: float(pos.split(",")[1]), pos_list))
    min_lng = min(lng_list)
    max_lng = max(lng_list)
    min_lat = min(lat_list)
    max_lat = max(lat_list)
    return "%.6f,%.6f" %((min_lng + max_lng) / 2, (min_lat + max_lat) / 2), paths#.split("|")[0]

# 添加SN签名校验
def generate_sn(params, SK):
    # 参数排序并编码
    sorted_params = sorted(params.items(), key=lambda x: x[0])
    query_string = '&'.join(
        f"{k}={urllib.parse.quote_plus(str(v))}" 
        for k, v in sorted_params
    )
  
    # 计算MD5签名
    sn = hashlib.md5(
        (query_string + SK).encode('utf-8')
    ).hexdigest()
  
    return sn

def route_map(AK, SK, paths):
    center, paths = get_center(paths)
    print ("center", center)
    base_url = "https://api.map.baidu.com/direction/v2/driving"
    base_url = "https://api.map.baidu.com/staticimage/v2/"
  
    # 构建基础参数
    params = {
        'ak': AK,
        'center': center,
        'paths': paths,
        #'scaler': "2",
        'timestamp': str(int(time.time()))
    }
    # # 生成SN签名
    # query = {
    #     'center': center,
    #     'scaler': "2",
    #     'paths' : paths,
    #     'ak': AK,
    #     'timestamp': str(int(time.time()))
    # }
    # encoded_str = urllib.parse.urlencode(query)
    # raw_str = f"/dstaticimage/v2?{encoded_str}{SK}"
    # sn = hashlib.md5(urllib.parse.quote_plus(raw_str).encode()).hexdigest()
    # # 带SN的请求URL
    # url = f"{base_url}?{encoded_str}&sn={sn}"
    # 生成签名并添加到参数
    params['sn'] = generate_sn(params, SK)
    # 构建完整请求URL
    base_url = "https://api.map.baidu.com/staticimage/v2?"
    encoded_params = '&'.join(
        f"{k}={urllib.parse.quote_plus(str(v))}" 
        for k, v in params.items()
    )
    request_url = base_url + encoded_params

    response = requests.get(request_url)
    # 假设response.text已经是乱码的形式
    html_content = response.text

    # 如果你知道原始的编码是ISO-8859-1，而实际应该是UTF-8，可以这样做：
    correctly_decoded_html = html_content.encode('iso-8859-1').decode('utf-8')

    # 现在你应该能看到正确的中文字符
    print (correctly_decoded_html)
    print (type(correctly_decoded_html))
